/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

// Hlavni trida serveru
public class Server extends Thread
{
	private String _ip = "127.0.0.1";
	private int _port = 2106;
	private ServerSocket _serverSocket;
	private static List<ClientThread> clients = new ArrayList<ClientThread>();

	public Server()
	{
		setName("Server"); // Nastaveni jmena vlakna
	}

	@Override
	public void run()
	{
		try
		{
			// Vytvori serverovy socket naslouchajici na zvolene IP adrese a portu
			_serverSocket = new ServerSocket(_port, 50, InetAddress.getByName(_ip));
			while (true)
			{
				Socket s = null;
				try
				{
					// Ceka na klienta, vlakno je pozastaveno dokud se nepripoji klient
					s = _serverSocket.accept();
				}
				catch (Exception e)
				{
				}
				if (s != null)
				{
					// Vytvori a priradi ke klientovi jeho vlastni vlakni
					ClientThread newclient = new ClientThread(s);
					clients.add(newclient);
					newclient.start();
				}
				try
				{
					Thread.sleep(100);
				}
				catch (InterruptedException ee)
				{
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			shutdown();
		}
	}

	// Uzavreni server socketu, odpojeni vsech klientu a vypnuti vlakna
	public void shutdown()
	{
		try
		{
			if (_serverSocket != null)
				_serverSocket.close();
			for (ClientThread clt : getClients())
				clt.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		this.interrupt();
	}

	// Vrati seznam vsech pripojenych klientu
	public static synchronized List<ClientThread> getClients()
	{
		return clients;
	}

	public static synchronized void RemoveClient(ClientThread client)
	{
		clients.remove(client);
	}
}
